//
//  LoginViewController.m
//  GoldOperationClient
//
//  Created by yaxue wang on 16/8/3.
//  Copyright © 2016年 展鸿科技. All rights reserved.
//

#import "LoginViewController.h"
#import "CTextField.h"
#import "TPKeyboardAvoidingScrollView.h"
#import "RegisterViewController.h"
#import "ResetPassViewController.h"
#import "AppDelegate.h"
#import "JPUSHService.h"

@interface LoginViewController ()
{
    CTextField* _phoneText;
    CTextField *_passwordText;
    NSInteger _eyeClick;
}
@property(nonatomic, strong)NSString *headUrl;
@property(nonatomic, strong)TPKeyboardAvoidingScrollView * scrollView;
@end
@implementation LoginViewController

- (void)initView
{
    [super initView];
    _eyeClick=0;
    self.navBar.hidden=YES;

    [self layContext];
    
    
}


- (void)layContext
{
    
    _scrollView =[[TPKeyboardAvoidingScrollView alloc]initWithFrame:CGRectMake(0, 0, WindowWidth, WindowHeight)];
    _scrollView.backgroundColor =[UIColor whiteColor];

    [self.view addSubview:_scrollView];
    UIImage *img=[UIImage imageNamed:@"Ico_login_head"];
    UIImageView *headImgaeView=[[UIImageView alloc]init];
    if(WindowHeight==480)
    {
        _scrollView.contentSize=CGSizeMake(WindowWidth, WindowHeight+100);
        headImgaeView.frame=CGRectMake((WindowWidth-img.size.width)/2, 50, img.size.width, img.size.height);
    }else
    {
        headImgaeView.frame=CGRectMake((WindowWidth-img.size.width)/2, 80, img.size.width, img.size.height);
        
    }
    headImgaeView.image=img;
    [_scrollView addSubview:headImgaeView];
    UIImage *icon=[UIImage imageNamed:@"Ico_login_phone"];
    for (int i=0; i<2; i++) {
        
        UIView *bgView =[[UIView alloc]initWithFrame:CGRectMake(40, CGRectGetMaxY(headImgaeView.frame)+72*i, WindowWidth-80, 72)];
        bgView.backgroundColor =[UIColor whiteColor];
        [_scrollView addSubview:bgView];
        UIImageView*iconImg=[[UIImageView alloc]init];
        iconImg.frame =CGRectMake(0, 44, icon.size.width, icon.size.height);
        if (i==0) {
            iconImg.image=[UIImage imageNamed:@"Ico_login_phone"];
            
        }else
        {
            iconImg.image=[UIImage imageNamed:@"Ico_login_password"];
            
        }
        [bgView addSubview:iconImg];
        
        UILabel*line=[[UILabel alloc]initWithFrame:CGRectMake(0, 71.5, WindowWidth-80, 0.5)];
        line.backgroundColor =LineColor;
        [bgView addSubview:line];
        if(i==0)
        {
            _phoneText =[[CTextField alloc]initWithFrame:CGRectMake(CGRectGetMaxX(iconImg.frame)+10, 72-40, bgView.bounds.size.width-CGRectGetMaxX(iconImg.frame)-10, 40)];
            _phoneText.placeholder =@"请输入手机号";
            [_phoneText setNullMsg:@"请输入11位手机号!"];
            _phoneText.font =F(12);
            [_phoneText setInputType:CTextFieldInputTypePhone];
            _phoneText.tag =100;
            [bgView addSubview:_phoneText];
        }else
        {
            _passwordText =[[CTextField alloc]initWithFrame:CGRectMake(CGRectGetMaxX(iconImg.frame)+10, 72-40, bgView.bounds.size.width-CGRectGetMaxX(iconImg.frame)-10-40, 40)];
            _passwordText.font =F(12);
            _passwordText.tag =100+i;
            [_passwordText setInputType:CTextFieldInputTypePassword];
            [_passwordText setBk_shouldChangeCharactersInRangeWithReplacementStringBlock:^BOOL(UITextField *textField, NSRange range, NSString *str) {
                NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:@"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"] invertedSet];
                NSString *filtered = [[str componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];
                return [str isEqualToString:filtered];
            }];
            
            [_passwordText setMinLength:8 msg:@"请输入8-20位密码!"];
            [_passwordText setMaxLength:20 LengthChangeBlock:nil];
            _passwordText.secureTextEntry =YES;
            _passwordText.placeholder = @"请输入密码";
            [_passwordText setNullMsg:@"请输入密码"];
            [bgView addSubview:_passwordText];
            [_passwordText bk_addEventHandler:^(id sender) {
                //移除表情
                NSString *newStr= [CClass disable_emoji:_passwordText.text];
                _passwordText.text=newStr;
                
                
            } forControlEvents:UIControlEventEditingChanged];
            
            UIButton *button =[UIButton buttonWithType:UIButtonTypeCustom];
            button.frame =CGRectMake(bgView.bounds.size.width-CGRectGetMaxX(iconImg.frame)-40+10, 72-33, 40, 33);
            [button setImage:[UIImage imageNamed:@"Ico_register_noEye"] forState:UIControlStateNormal];
            [button bk_addEventHandler:^(id sender) {
                _eyeClick++;
                if (_eyeClick%2==0) {
                    _passwordText.secureTextEntry=YES;
                    [button setImage:[UIImage imageNamed:@"Ico_register_noEye"] forState:UIControlStateNormal];
                    
                }else{
                    _passwordText.secureTextEntry=NO;
                    [button setImage:[UIImage imageNamed:@"Ico_register_eye"] forState:UIControlStateNormal];
                }
            } forControlEvents:UIControlEventTouchUpInside];
            [bgView addSubview:button];
        }
        
        
    }
    UIButton *btnFogot = [[UIButton alloc] initWithFrame:CGRectMake(WindowWidth-120, CGRectGetMaxY(headImgaeView.frame)+72*2, 120, 50)];
    [_scrollView addSubview:btnFogot];
    [btnFogot setTitleColor:MainColor forState:UIControlStateNormal];
    [btnFogot setTitle:@"忘记密码?" forState:UIControlStateNormal];
    [btnFogot.titleLabel setFont:F(13)];
    [btnFogot bk_addEventHandler:^(id sender) {
        _passwordText.text = @"";
        ResetPassViewController *fogotPasswordViewController = [[ResetPassViewController alloc] init];
        [self pushController:fogotPasswordViewController];
    } forControlEvents:UIControlEventTouchUpInside];
    
    UIButton *loginBtn =[UIButton buttonWithType:UIButtonTypeCustom];
    loginBtn.frame =CGRectMake(44,CGRectGetMaxY(btnFogot.frame), WindowWidth-88, 38);
    [loginBtn setBackgroundColor:MainColor];
    loginBtn.layer.masksToBounds=YES;
    loginBtn.layer.cornerRadius=8;
    [loginBtn setTitle:@"确定" forState:UIControlStateNormal];
    loginBtn.titleLabel.font =F(15);
    [loginBtn bk_addEventHandler:^(id sender) {
       
        if (!_phoneText.verfiy) {
            return;
        }
        
        [self setIsLoading:YES];
        NSMutableDictionary *dic = [NSMutableDictionary dictionary];
        [dic setObject:_phoneText.value forKey:@"mobile"];
        [dic setObject:@"02" forKey:@"customerType"];
        [dic setObject:[CClass base64:_passwordText.text] forKey:@"password"];
        [dic setObject:[CClass getUUID] forKey:@"imei"];
        
        [CClass HttpRequestTask:YES withUrl:@"app_login" withData:dic notifyError:YES onSuccess:^(BaseModel *model) {
 
            [(AppDelegate *)[[UIApplication sharedApplication] delegate] registerPush];
            [self setIsLoading:NO];
            self.headUrl=[model.B_data objectForKey:@"headImg"];
            [CClass saveCacheData:_phoneText.value key:NSUD_Mobile];
            [CClass saveCacheData:[model.B_data objectForKey:@"name"] key:NSUD_Name];
            [CClass saveCacheData:[model.B_data objectForKey:@"uuid"] key:NSUD_Uuid];
            //进入首页
            [CClass saveCacheData:[model.B_data objectForKey:@"authtoken"] key:NSUD_Token];
            [CClass saveCacheData:[model.B_data objectForKey:@"uuid"]key:NSUD_UUID];
            [CClass saveCacheData:[model.B_data objectForKey:@"state"] key:NSUD_state];
            if([F_NSpace([model.B_data  objectForKey:@"city"]) isEqualToString:@""]){
                
            }else
            {
                [CClass saveCacheData:[model.B_data objectForKey:@"city"]key:NSUD_City];
                
            }
            if([F_NSpace([model.B_data  objectForKey:@"province"]) isEqualToString:@""]){
                
            }else
            {
                [CClass saveCacheData:[model.B_data objectForKey:@"province"]key:NSUD_Province];
                
            }
            [self enter];

            //	获取七牛云存储信息
            [CClass HttpRequestTask:YES withUrl:@"warninglist_getQiniuInfo" withData:nil notifyError:YES onSuccess:^(BaseModel *model) {
                [CClass saveCacheData:[model.B_data objectForKey:@"qnDomain"] key:qnDomain];
                [CClass saveCacheData:[model.B_data objectForKey:@"qnScope"]key:qnScope];
                [CClass saveCacheData:[model.B_data objectForKey:@"qnAk"] key:qnAk];
                [CClass saveCacheData:[model.B_data objectForKey:@"qnSk"]key:qnSk];
                
                //存储头像
                NSString *string=[NSString stringWithFormat:@"%@%@",[CClass getCacheData:qnDomain],self.headUrl];
                UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:string]]];
                [CClass SaveImageToLocal:image Keys:NSUD_HeadImg];
                [self setIsLoading:NO];

              
            } onError:^(BaseModel *model) {
                
            }];
        } onError:^(BaseModel *model) {
            loginBtn.userInteractionEnabled=YES;
            [self setIsLoading:NO];

        }];

    } forControlEvents:UIControlEventTouchUpInside];
    [_scrollView addSubview:loginBtn];
    
    
    UIButton *registerBtn =[UIButton buttonWithType:UIButtonTypeCustom];
    registerBtn.frame =CGRectMake(44, CGRectGetMaxY(loginBtn.frame)+15, WindowWidth-88, 38);
    [registerBtn setBackgroundColor:[UIColor whiteColor]];
    registerBtn.layer.masksToBounds=YES;
    registerBtn.layer.cornerRadius=8;
    registerBtn.layer.borderColor=MainColor.CGColor;
    registerBtn.layer.borderWidth=1;
    [registerBtn setTitleColor:MainColor forState:UIControlStateNormal];
    [registerBtn setTitle:@"注册" forState:UIControlStateNormal];
    registerBtn.titleLabel.font =F(15);
    [registerBtn bk_addEventHandler:^(id sender) {
        RegisterViewController *registerVC =[[RegisterViewController alloc]init];
        [self pushController:registerVC];
    } forControlEvents:UIControlEventTouchUpInside];
    [_scrollView addSubview:registerBtn];
    
}
- (void) enter{
    [self.navigationController popToRootViewControllerAnimated:NO];
    AppDelegate *delegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    [delegate enter];
}
@end
